<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { pageMovies, searchMovies } from '@/api/movies'
import { VideoCamera, Search, StarFilled } from '@element-plus/icons-vue'

const router = useRouter()

const keyword = ref('')
const type = ref('')
const status = ref('')
const pageNo = ref(1)
const pageSize = ref(12)
const total = ref(0)
const items = ref([])
const loading = ref(false)

const cleanUrl = (url) => (url ? String(url).replace(/`/g, '').trim() : '')
const posterSrc = (m) => cleanUrl(m?.posterUrl) || cleanUrl(m?.imageUrl) || cleanUrl(m?.poster) || cleanUrl(m?.cover) || ''

const fetchList = async () => {
  loading.value = true
  try {
    const params = { pageNo: pageNo.value, pageSize: pageSize.value }
    let res
    if (keyword.value && keyword.value.trim()) {
      res = await searchMovies({ keyword: keyword.value.trim(), ...params })
    } else {
      res = await pageMovies({ mname: '', type: type.value || undefined, status: status.value || undefined, ...params })
    }
    if (res && (res.code === '200' || res.code === 200)) {
      items.value = res.data?.records || []
      total.value = res.data?.total || 0
    } else {
      ElMessage.error(res?.msg || '获取电影列表失败')
    }
  } catch (e) {
    console.error(e)
    ElMessage.error('网络异常，稍后重试')
  } finally {
    loading.value = false
  }
}

onMounted(fetchList)

const onSearch = () => {
  pageNo.value = 1
  fetchList()
}

const handleSizeChange = (s) => {
  pageSize.value = s
  pageNo.value = 1
  fetchList()
}
const handlePageChange = (p) => {
  pageNo.value = p
  fetchList()
}

const goHome = () => router.push('/')
const goDetail = (id) => router.push(`/movie/${id}`)
</script>

<template>
  <div class="page movies" v-loading="loading">
    <!-- 顶部导航 -->
    <div class="topbar">
      <div class="brand" @click="goHome">
        <el-icon><VideoCamera /></el-icon>
        <span>电影列表</span>
      </div>
      <div class="actions">
        <el-link type="primary" @click="goHome">首页</el-link>
      </div>
    </div>

    <!-- 英雄区：搜索与筛选 -->
    <section class="hero glass">
      <h1 class="title">发现好电影</h1>
      <p class="subtitle">按名称关键字搜索，并可选择类型与状态</p>
      <div class="toolbar">
        <el-input v-model="keyword" placeholder="输入关键字（名称/类型）" clearable class="input">
          <template #prepend>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="type" placeholder="类型" clearable class="select">
          <el-option label="全部" value="" />
          <el-option label="科幻" value="科幻" />
          <el-option label="动作" value="动作" />
          <el-option label="喜剧" value="喜剧" />
          <el-option label="悬疑" value="悬疑" />
          <el-option label="爱情" value="爱情" />
          <el-option label="动画" value="动画" />
          <el-option label="纪录片" value="纪录片" />
        </el-select>
        <el-select v-model="status" placeholder="状态" clearable class="select">
          <el-option label="全部" value="" />
          <el-option label="热门" value="HOT" />
          <el-option label="下线" value="OFFLINE" />
        </el-select>
        <el-button type="primary" @click="onSearch">搜索</el-button>
      </div>
    </section>

    <!-- 列表区 -->
    <section class="content">
      <div v-if="items.length" class="grid">
        <el-card
          v-for="m in items"
          :key="m.id"
          class="card clickable"
          shadow="hover"
          @click="m.id && goDetail(m.id)"
        >
          <div class="poster">
            <img :src="posterSrc(m)" :alt="m.mname || m.title" />
          </div>
          <div class="info">
            <h3 class="name">{{ m.mname || m.title }}</h3>
            <div class="meta-row">
              <span class="type">{{ m.type || '电影' }}</span>
              <span class="rating" v-if="(m.rating || m.score)">
                <el-icon class="star"><StarFilled /></el-icon>
                {{ (m.rating || m.score).toFixed ? (m.rating || m.score).toFixed(1) : (m.rating || m.score) }}
              </span>
              <span class="price" v-if="m.price">￥{{ m.price }}</span>
            </div>
          </div>
          <div class="card-footer">
            <el-button type="primary" text @click.stop="goDetail(m.id)">查看详情</el-button>
          </div>
        </el-card>
      </div>
      <el-empty v-else description="暂无电影数据" />

      <div class="pager" v-if="total > 0">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next"
          :total="total"
          :page-sizes="[8,12,16,24]"
          :page-size="pageSize"
          :current-page="pageNo"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </section>
  </div>
</template>

<style scoped>
.page { min-height: 100vh; background: radial-gradient(1000px 500px at 10% 10%, rgba(99,102,241,0.15), transparent), radial-gradient(800px 400px at 90% 0%, rgba(16,185,129,0.12), transparent), #0b1020; color: #e5e7eb; }
.topbar { display: flex; align-items: center; justify-content: space-between; padding: 16px 24px; }
.brand { display: flex; align-items: center; gap: 8px; cursor: pointer; font-weight: 600; letter-spacing: 0.6px; }
.actions :deep(.el-link) { margin-left: 12px; }

.hero { margin: 16px auto 24px; padding: 20px 24px; max-width: 980px; border-radius: 16px; background: rgba(255,255,255,0.12); backdrop-filter: blur(12px); border: 1px solid rgba(255,255,255,0.22); }
.title { font-size: 24px; font-weight: 700; margin: 0 0 6px; }
.subtitle { margin: 0; color: #cfd3dc; }
.toolbar { margin-top: 12px; display: flex; gap: 10px; }
.input { width: 320px; }
.select { width: 160px; }

.content { max-width: 980px; margin: 0 auto 40px; padding: 0 12px; }
.grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px; }
@media (max-width: 1000px) { .grid { grid-template-columns: repeat(2, 1fr); } }
@media (max-width: 700px) { .grid { grid-template-columns: 1fr; } }

.card :deep(.el-card__body) { padding: 0; overflow: hidden; }
.poster img { width: 100%; height: 220px; object-fit: cover; display: block; }
.info { padding: 10px 12px; }
.name { font-weight: 600; color: #1f2b38; }
.meta-row { margin-top: 4px; display: flex; align-items: center; gap: 8px; color: #606266; }
.star { color: #ffd04b; margin-right: 2px; }
.clickable { cursor: pointer; }
.card-footer { padding: 10px 12px; }
.pager { display: flex; justify-content: center; margin-top: 8px; }
</style>